<?php
declare (strict_types = 1);


namespace app\index\controller;
use think\facade\View;
use think\facade\Db;
use think\facade\Request;
class ArticleList
{
    public function index()
    {
        $where=[];
        $member_id=input("member_id",0,"intval");
        if(!$member_id){
            return error("缺少member_id");
        }
        View::assign("member_id",$member_id);
        $where[]=["member_id","=",$member_id];
        $cat_list=\app\common\model\ArticleClass::where($where)->order("sort asc,id asc")->select();
        View::assign("cat_list",$cat_list);
        //
        $where=[];
        $title="所有信息";
        $class_id=input("class_id",0,"intval");
        if($class_id){
            $where[]=["article_class_id","=",$class_id];
            $cat=\app\common\model\ArticleClass::find($class_id);
            $title=$cat['name'];
            $this->autoPush($class_id);
            //
        }
        View::assign("title",$title);
        $where[]=["state","=",3];
        $list=\app\common\model\Article::where($where)->order("push_time desc")->paginate(50);
        View::assign("list",$list->items());
        View::assign("page",$list->render());
        return View::fetch();
    }
    public function show()
    {
        $where=[];
        $id=input("id",0,"intval");
        if(!$id){
            return error("缺少id");
        }
        $info=\app\common\model\Article::find($id);
        View::assign("info",$info);
        return View::fetch();
    }
    /*
     * 根据article_class_id判断article表里的最大的push_time值是否大于今天0时的时间戳，如果没有则随机更新article_class表里50条的push_time为当前时间戳
     */
    private function autoPush($article_class_id){
        $maxPushTime=\app\common\model\Article::where([
            ["article_class_id","=",$article_class_id],
            ["state","=",3]
        ])->max("push_time");
        //将今日0时的时间戳和$maxPushTime比对，如果$maxPushTime小于今日0时的时间戳，则随机更新article_class表里50条的push_time为当前时间戳
        if($maxPushTime<strtotime(date("Y-m-d"))){
            $where=[];
            $where[]=["article_class_id","=",$article_class_id];
            $where[]=["state","=",2];
            $list=\app\common\model\Article::where($where)->orderRaw("rand()")->limit(10)->select();
            if($list){
                foreach ($list as $k=>$v){
                    $v->push_time=date("Y-m-d H:i:s");
                    $v->state=3;
                    $v->save();
                }
            }
        }


    }

}
